import React, { useState, useEffect } from 'react';
import {
  Table,
  Card,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  DatePicker,
  message,
  Popconfirm,
  Tag,
  Avatar,
  Typography,
  Row,
  Col,
  Statistic,
  Descriptions,
  Tabs
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  UserOutlined,
  EyeOutlined,
  ReloadOutlined,
  ShoppingCartOutlined
} from '@ant-design/icons';
import dayjs from 'dayjs';
import { userAPI, orderAPI, analyticsAPI } from '../../services/api';

const { Title } = Typography;
const { Option } = Select;
const { TabPane } = Tabs;

const UserManagement = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState(null);
  const [selectedUser, setSelectedUser] = useState(null);
  const [userOrders, setUserOrders] = useState([]);
  const [userProfile, setUserProfile] = useState(null);
  const [form] = Form.useForm();
  const [searchText, setSearchText] = useState('');
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [stats, setStats] = useState({
    totalUsers: 0,
    activeUsers: 0,
    newUsersToday: 0
  });

  // 用户状态选项
  const statusOptions = [
    { label: '正常', value: 'ACTIVE', color: 'green' },
    { label: '禁用', value: 'DISABLED', color: 'red' },
    { label: '待验证', value: 'PENDING', color: 'orange' }
  ];

  // 加载用户列表
  const loadUsers = async (page = 1, pageSize = 10, keyword = '') => {
    setLoading(true);
    try {
      let response;
      if (keyword.trim()) {
        response = await userAPI.search(keyword);
        // 搜索结果转换为分页格式
        const startIndex = (page - 1) * pageSize;
        const endIndex = startIndex + pageSize;
        const paginatedData = response.slice(startIndex, endIndex);
        
        setUsers(paginatedData);
        setPagination(prev => ({
          ...prev,
          current: page,
          total: response.length
        }));
      } else {
        response = await userAPI.getAll(page - 1, pageSize);
        if (response?.content) {
          setUsers(response.content);
          setPagination(prev => ({
            ...prev,
            current: page,
            total: response.totalElements
          }));
        } else if (Array.isArray(response)) {
          setUsers(response);
          setPagination(prev => ({
            ...prev,
            current: page,
            total: response.length
          }));
        }
      }
    } catch (error) {
      console.error('加载用户列表失败:', error);
      message.error('加载用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载统计数据
  const loadStats = async () => {
    try {
      const response = await userAPI.getStats();
      setStats({
        totalUsers: response.totalUsers || 0,
        activeUsers: response.activeUsers || 0,
        newUsersToday: response.newUsersToday || 0
      });
    } catch (error) {
      console.error('加载统计数据失败:', error);
    }
  };

  // 搜索用户
  const handleSearch = (value) => {
    setSearchText(value);
    setPagination(prev => ({ ...prev, current: 1 }));
    loadUsers(1, pagination.pageSize, value);
  };

  // 分页变化
  const handleTableChange = (paginationConfig) => {
    setPagination(paginationConfig);
    loadUsers(paginationConfig.current, paginationConfig.pageSize, searchText);
  };

  // 打开新增/编辑模态框
  const handleOpenModal = (user = null) => {
    setEditingUser(user);
    setModalVisible(true);
    if (user) {
      form.setFieldsValue({
        ...user,
        birthDate: user.birthDate ? dayjs(user.birthDate) : null
      });
    } else {
      form.resetFields();
      form.setFieldsValue({
        status: 'ACTIVE'
      });
    }
  };

  // 关闭模态框
  const handleCloseModal = () => {
    setModalVisible(false);
    setEditingUser(null);
    form.resetFields();
  };

  // 保存用户
  const handleSaveUser = async (values) => {
    try {
      const userData = {
        ...values,
        birthDate: values.birthDate ? values.birthDate.format('YYYY-MM-DD') : null
      };

      if (editingUser) {
        await userAPI.update(editingUser.id, userData);
        message.success('用户更新成功');
      } else {
        await userAPI.create(userData);
        message.success('用户创建成功');
      }

      handleCloseModal();
      loadUsers(pagination.current, pagination.pageSize, searchText);
      loadStats();
    } catch (error) {
      console.error('保存用户失败:', error);
      message.error('保存用户失败');
    }
  };

  // 删除用户
  const handleDeleteUser = async (id) => {
    try {
      await userAPI.delete(id);
      message.success('用户删除成功');
      loadUsers(pagination.current, pagination.pageSize, searchText);
      loadStats();
    } catch (error) {
      console.error('删除用户失败:', error);
      message.error('删除用户失败');
    }
  };

  // 查看用户详情
  const handleViewUser = async (user) => {
    setSelectedUser(user);
    setDetailModalVisible(true);
    
    try {
      // 加载用户订单
      const orders = await orderAPI.getUserOrders(user.id);
      setUserOrders(Array.isArray(orders) ? orders : orders?.content || []);
      
      // 加载用户画像
      const profile = await analyticsAPI.getUserProfile(user.id);
      setUserProfile(profile);
    } catch (error) {
      console.error('加载用户详情失败:', error);
      message.error('加载用户详情失败');
    }
  };

  // 刷新数据
  const handleRefresh = () => {
    loadUsers(pagination.current, pagination.pageSize, searchText);
    loadStats();
  };

  // 初始加载
  useEffect(() => {
    loadUsers();
  }, []);

  // 当用户列表变化时更新统计
  useEffect(() => {
    loadStats();
  }, [users]);

  // 获取状态配置
  const getStatusConfig = (status) => {
    return statusOptions.find(option => option.value === status) || statusOptions[0];
  };

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80
    },
    {
      title: '头像',
      dataIndex: 'avatar',
      key: 'avatar',
      width: 80,
      render: (avatar, record) => (
        <Avatar
          size={40}
          src={avatar}
          icon={<UserOutlined />}
          style={{ backgroundColor: '#1890ff' }}
        >
          {!avatar && record.username?.charAt(0)?.toUpperCase()}
        </Avatar>
      )
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      ellipsis: true
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      ellipsis: true
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      width: 120
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => {
        const config = getStatusConfig(status);
        return <Tag color={config.color}>{config.label}</Tag>;
      },
      filters: statusOptions.map(option => ({
        text: option.label,
        value: option.value
      })),
      onFilter: (value, record) => record.status === value
    },
    {
      title: '注册时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 120,
      render: (date) => date ? dayjs(date).format('YYYY-MM-DD') : '-',
      sorter: (a, b) => dayjs(a.createdAt).unix() - dayjs(b.createdAt).unix()
    },
    {
      title: '最后登录',
      dataIndex: 'lastLoginAt',
      key: 'lastLoginAt',
      width: 120,
      render: (date) => date ? dayjs(date).format('YYYY-MM-DD') : '从未登录'
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleViewUser(record)}
            size="small"
          >
            详情
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleOpenModal(record)}
            size="small"
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个用户吗？"
            onConfirm={() => handleDeleteUser(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              danger
              icon={<DeleteOutlined />}
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  // 订单表格列
  const orderColumns = [
    {
      title: '订单ID',
      dataIndex: 'id',
      key: 'id',
      width: 100
    },
    {
      title: '订单金额',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      render: (amount) => `¥${parseFloat(amount || 0).toFixed(2)}`
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        const colorMap = {
          'PENDING': 'orange',
          'PAID': 'green',
          'SHIPPED': 'blue',
          'DELIVERED': 'green',
          'CANCELLED': 'red'
        };
        return <Tag color={colorMap[status] || 'default'}>{status}</Tag>;
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date) => date ? dayjs(date).format('YYYY-MM-DD HH:mm') : '-'
    }
  ];

  return (
    <div className="user-management">
      {/* 页面头部 */}
      <div className="page-header">
        <Title level={2}>用户管理</Title>
      </div>

      {/* 统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        <Col xs={24} sm={8}>
          <Card>
            <Statistic
              title="用户总数"
              value={stats.totalUsers}
              prefix={<UserOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={8}>
          <Card>
            <Statistic
              title="活跃用户"
              value={stats.activeUsers}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={8}>
          <Card>
            <Statistic
              title="今日新增"
              value={stats.newUsersToday}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 操作工具栏 */}
      <Card className="toolbar-card">
        <Row justify="space-between" align="middle">
          <Col>
            <Space>
              <Input.Search
                placeholder="搜索用户名或邮箱"
                allowClear
                style={{ width: 300 }}
                onSearch={handleSearch}
                enterButton={<SearchOutlined />}
              />
            </Space>
          </Col>
          <Col>
            <Space>
              <Button
                icon={<ReloadOutlined />}
                onClick={handleRefresh}
              >
                刷新
              </Button>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => handleOpenModal()}
              >
                新增用户
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 用户表格 */}
      <Card className="table-card">
        <Table
          columns={columns}
          dataSource={users}
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
          }}
          onChange={handleTableChange}
          rowKey="id"
          scroll={{ x: 1000 }}
        />
      </Card>

      {/* 新增/编辑用户模态框 */}
      <Modal
        title={editingUser ? '编辑用户' : '新增用户'}
        open={modalVisible}
        onCancel={handleCloseModal}
        footer={null}
        width={600}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSaveUser}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="username"
                label="用户名"
                rules={[{ required: true, message: '请输入用户名' }]}
              >
                <Input placeholder="请输入用户名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="email"
                label="邮箱"
                rules={[
                  { required: true, message: '请输入邮箱' },
                  { type: 'email', message: '请输入有效的邮箱地址' }
                ]}
              >
                <Input placeholder="请输入邮箱" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="phone"
                label="手机号"
              >
                <Input placeholder="请输入手机号" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="status"
                label="状态"
                rules={[{ required: true, message: '请选择状态' }]}
              >
                <Select placeholder="请选择状态">
                  {statusOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="realName"
                label="真实姓名"
              >
                <Input placeholder="请输入真实姓名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="birthDate"
                label="出生日期"
              >
                <DatePicker
                  style={{ width: '100%' }}
                  placeholder="请选择出生日期"
                  format="YYYY-MM-DD"
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="address"
            label="地址"
          >
            <Input placeholder="请输入地址" />
          </Form.Item>

          {!editingUser && (
            <Form.Item
              name="password"
              label="密码"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password placeholder="请输入密码" />
            </Form.Item>
          )}

          <Form.Item>
            <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
              <Button onClick={handleCloseModal}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                {editingUser ? '更新' : '创建'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 用户详情模态框 */}
      <Modal
        title="用户详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={null}
        width={800}
        destroyOnClose
      >
        {selectedUser && (
          <Tabs defaultActiveKey="1">
            <TabPane tab="基本信息" key="1">
              <Descriptions bordered column={2}>
                <Descriptions.Item label="用户ID">{selectedUser.id}</Descriptions.Item>
                <Descriptions.Item label="用户名">{selectedUser.username}</Descriptions.Item>
                <Descriptions.Item label="邮箱">{selectedUser.email}</Descriptions.Item>
                <Descriptions.Item label="手机号">{selectedUser.phone || '-'}</Descriptions.Item>
                <Descriptions.Item label="真实姓名">{selectedUser.realName || '-'}</Descriptions.Item>
                <Descriptions.Item label="出生日期">
                  {selectedUser.birthDate ? dayjs(selectedUser.birthDate).format('YYYY-MM-DD') : '-'}
                </Descriptions.Item>
                <Descriptions.Item label="地址" span={2}>{selectedUser.address || '-'}</Descriptions.Item>
                <Descriptions.Item label="状态">
                  <Tag color={getStatusConfig(selectedUser.status).color}>
                    {getStatusConfig(selectedUser.status).label}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="注册时间">
                  {selectedUser.createdAt ? dayjs(selectedUser.createdAt).format('YYYY-MM-DD HH:mm') : '-'}
                </Descriptions.Item>
                <Descriptions.Item label="最后登录">
                  {selectedUser.lastLoginAt ? dayjs(selectedUser.lastLoginAt).format('YYYY-MM-DD HH:mm') : '从未登录'}
                </Descriptions.Item>
              </Descriptions>
            </TabPane>
            
            <TabPane tab="订单记录" key="2">
              <Table
                columns={orderColumns}
                dataSource={userOrders}
                pagination={{ pageSize: 5 }}
                size="small"
                rowKey="id"
              />
            </TabPane>
            
            <TabPane tab="用户画像" key="3">
              {userProfile ? (
                <Descriptions bordered column={2}>
                  <Descriptions.Item label="偏好分类">{userProfile.preferredCategory || '-'}</Descriptions.Item>
                  <Descriptions.Item label="消费水平">{userProfile.spendingLevel || '-'}</Descriptions.Item>
                  <Descriptions.Item label="活跃度">{userProfile.activityLevel || '-'}</Descriptions.Item>
                  <Descriptions.Item label="购买频率">{userProfile.purchaseFrequency || '-'}</Descriptions.Item>
                </Descriptions>
              ) : (
                <div style={{ textAlign: 'center', padding: '40px' }}>
                  暂无用户画像数据
                </div>
              )}
            </TabPane>
          </Tabs>
        )}
      </Modal>
    </div>
  );
};

export default UserManagement;